package jmind.asteroidea.plugin.spring;

import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.core.DefaultParameterNameDiscoverer;
import org.springframework.util.ClassUtils;
import org.springframework.util.ReflectionUtils;

import java.beans.Introspector;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * description:BeanNameGenerator 有三个实现：
 * DefaultBeanNameGenerator
 * AnnotationBeanNameGenerator
 * FullyQualifiedAnnotationBeanNameGenerator
 * @author weibo.xie
 * @date:2022/7/12 上午11:14
 */
public class SpringBeanUtil {

   public static String getBeanName(Class clazz) {
        String shortClassName = ClassUtils.getShortName(clazz.getSimpleName());
        // 根据类名来生成 bean name
        return Introspector.decapitalize(shortClassName);
    }


    public static  String[] getParameterNames(Method method) {
        DefaultParameterNameDiscoverer discover = new DefaultParameterNameDiscoverer();
        String[] parameterNames = discover.getParameterNames(method);
        return parameterNames;
    }


    private Object createInterfaceProxyForFactoryBean(final Object factoryBean, Class<?> interfaceType,
                                                      final ConfigurableBeanFactory beanFactory, final String beanName) {

        return Proxy.newProxyInstance(
                factoryBean.getClass().getClassLoader(), new Class<?>[] {interfaceType},
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        if (method.getName().equals("getObject") && args == null) {
                            return beanFactory.getBean(beanName);
                        }
                        return ReflectionUtils.invokeMethod(method, factoryBean, args);
                    }
                });
    }

}
